package orz.itrip.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import orz.itrip.*;
import orz.itrip.biz.service.HotelOrderService;
import orz.itrip.biz.vo.GetOrderListVo;
import orz.itrip.mapper.HotelRoomMapper;
import orz.itrip.mapper.OrderLinkUserMapper;
import orz.itrip.pojo.OrderLinkUser;
import orz.itrip.vo.GetPreOrderVo;
import orz.itrip.vo.HotelOrderAddVo;
import orz.itrip.vo.HotelOrderRoomVo;
import orz.itrip.vo.HotelOrderVo;
import orz.itrip.dto.Dto;
import orz.itrip.mapper.HotelOrderMapper;
import orz.itrip.pojo.HotelOrder;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class HotelOrderServiceImpl implements HotelOrderService {
    @Resource
    private HotelOrderMapper hotelOrderMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private HotelRoomMapper hotelRoomMapper;
    @Resource
    private OrderLinkUserMapper orderLinkUserMapper;

    @Override
    public Dto getpersonalorderlist(GetOrderListVo getOrderListVo,String token) throws ParseException {
        if (getOrderListVo.getPageNo()==null){
            getOrderListVo.setPageNo(1);
        }
        JSONObject jsonObject = JSON.parseObject(stringRedisTemplate.opsForValue().get(token));
        Page page = PageHelper.startPage(getOrderListVo.getPageNo(),getOrderListVo.getPageSize(),true);
        HotelOrder hotelOrder = new HotelOrder();
        hotelOrder.setOrderNo(getOrderListVo.getOrderNo());
        if (!StringUtils.isEmpty(getOrderListVo.getEndDate())){
            hotelOrder.setCheckOutDate(new SimpleDateFormat("yyyy-MM-dd").parse(getOrderListVo.getEndDate()));
        }
        if (!StringUtils.isEmpty(getOrderListVo.getStartDate())){
            hotelOrder.setCheckInDate(new SimpleDateFormat("yyyy-MM-dd").parse(getOrderListVo.getStartDate()));
        }
        hotelOrder.setUserId(jsonObject.getLong("id"));
        hotelOrder.setLinkUserName(getOrderListVo.getLinkUserName());
        PageUtils<HotelOrder> pageUtils = new PageUtils<>();
        pageUtils.setCurPage(getOrderListVo.getPageNo());
        pageUtils.setBeginPos(page.getStartRow());
        pageUtils.setPageSize(getOrderListVo.getPageSize());
        pageUtils.setPageCount(getOrderListVo.getPageSize());
        List<HotelOrder> hotelOrders = null;
        if (getOrderListVo.getOrderType()!=null){
            if (getOrderListVo.getOrderType()!=-1){
                if (getOrderListVo.getOrderStatus()!=-1){
                    hotelOrder.setOrderStatus(getOrderListVo.getOrderStatus());
                }
                hotelOrder.setOrderType(getOrderListVo.getOrderType());
                hotelOrders = hotelOrderMapper.selectByLike(hotelOrder);
            }else {
                if (getOrderListVo.getOrderStatus()!=-1){
                    hotelOrder.setOrderStatus(getOrderListVo.getOrderStatus());
                }
                hotelOrders = hotelOrderMapper.selectByLike(hotelOrder);
            }
        }
        pageUtils.setTotal(page.getTotal());
        pageUtils.setRows(hotelOrders);
        return DtoUtils.getSuccesWithData(pageUtils,"获取个人订单列表成功");
    }

    @Override
    public Dto getpersonalorderinfo(Long orderId, String token) {
        JSONObject jsonObject = JSON.parseObject(stringRedisTemplate.opsForValue().get(token));
        HotelOrder hotelOrder = new HotelOrderVo();
        hotelOrder.setId(orderId);
        hotelOrder.setUserId(jsonObject.getLong("id"));
        HotelOrderVo hotelOrderVo = hotelOrderMapper.selectVo(hotelOrder);
        System.out.println(hotelOrderVo.getPayAmount());
        if (hotelOrderVo!=null){
            if (hotelOrderVo.getOrderStatus()!=1){
                if (hotelOrderVo.getOrderStatus()==2){
                    hotelOrderVo.setProcessNode(3);
                }else if (hotelOrderVo.getOrderStatus()==3){
                    hotelOrderVo.setProcessNode(4);
                }else if (hotelOrderVo.getOrderStatus()==4){
                    hotelOrderVo.setProcessNode(6);
                }else if (hotelOrderVo.getOrderStatus()==0){
                    hotelOrderVo.setProcessNode(2);
                }
                hotelOrderVo.setOrderProcess(StaticStringUtils.ORDERPROCESS_STATUS_2);
            }else {
                hotelOrderVo.setProcessNode(3);
                hotelOrderVo.setOrderProcess(StaticStringUtils.ORDERPROCESS_STATUS_1);
            }
            return DtoUtils.getSuccesWithData(hotelOrderVo,"获取个人订单信息成功");
        }
        return DtoUtils.getFalseDto("获取个人订单信息失败","30001");
    }

    @Override
    public Dto getpersonalorderroominfo(Long orderId, String token) {
        JSONObject jsonObject = JSON.parseObject(stringRedisTemplate.opsForValue().get(token));
        HotelOrder hotelOrder = new HotelOrderVo();
        hotelOrder.setId(orderId);
        hotelOrder.setUserId(jsonObject.getLong("id"));
        HotelOrderRoomVo hotelOrderRoomVo = hotelOrderMapper.selectVoRoom(hotelOrder);
        if (hotelOrderRoomVo!=null){
            hotelOrderRoomVo.setCheckInWeek(DateUtils.getWeek(hotelOrderRoomVo.getCheckInDate()));
            hotelOrderRoomVo.setCheckOutWeek(DateUtils.getWeek(hotelOrderRoomVo.getCheckOutDate()));

            return DtoUtils.getSuccesWithData(hotelOrderRoomVo,"获取个人订单房型信息成功");
        }
        return DtoUtils.getFalseDto("获取个人订单房型信息失败","30002");
    }

    @Override
    public Dto getpreorderinfo(GetPreOrderVo getPreOrderVo) {
        //获取temp表中日期范围内的最小库存
        Integer store = hotelOrderMapper.selectStore(getPreOrderVo);
        if (store==null){
            //获取日期范围内product表中的库存
            store = hotelOrderMapper.selectProduct(getPreOrderVo);
        }
        //获取日期范围内未付款的订单数
        Integer noPayOrderScore = hotelOrderMapper.selectOrderScore(getPreOrderVo);
        if (noPayOrderScore==null){
            noPayOrderScore = 0;
        }
        GetPreOrderVo getPreOrder = hotelOrderMapper.selectGetPre(getPreOrderVo);
        if (getPreOrder!=null){
            getPreOrderVo.setStore(store-noPayOrderScore);
            getPreOrderVo.setPrice(getPreOrder.getPrice());
            getPreOrderVo.setHotelName(getPreOrder.getHotelName());
            return DtoUtils.getSuccesWithData(getPreOrderVo,"获取成功");
        }
        return DtoUtils.getFalseDto("获取失败","30003");
    }

    @Override
    public Dto addhotelorder(HotelOrderAddVo hotelOrderAddVo,String token) {
        JSONObject jsonObject = JSON.parseObject(stringRedisTemplate.opsForValue().get(token));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderNo = System.getenv().get("USERDOMAIN").replace("-","").substring(1,6) + simpleDateFormat.format(new Date()) + UUIDUtils.getStr(6,false);
        HotelOrder hotelOrder = new HotelOrder();
        BeanUtils.copyProperties(hotelOrderAddVo,hotelOrder);//将一个对象中的所有值复制到另一个对象中
        double days = Math.ceil((hotelOrderAddVo.getCheckOutDate().getTime() - hotelOrderAddVo.getCheckInDate().getTime())/1000/60/60/24);
        if (token.startsWith("token:pc")){
            hotelOrder.setBookType(0);
        }else if (token.startsWith("token:mobile")){
            hotelOrder.setBookType(1);
        }else {
            hotelOrder.setBookType(2);
        }
        hotelOrder.setPayAmount(hotelRoomMapper.selectPrice(hotelOrderAddVo.getRoomId())*hotelOrderAddVo.getCount());
        hotelOrder.setBookingDays((int) days);
        hotelOrder.setOrderStatus(0);
        hotelOrder.setOrderNo(orderNo);
        hotelOrder.setUserId(jsonObject.getLong("id"));
        hotelOrder.setCreatedBy(jsonObject.getLong("id"));
        hotelOrder.setCreationDate(new Date());
        StringBuffer linkUserName = new StringBuffer();
        for (int i = 0; i < hotelOrderAddVo.getLinkUser().size(); i++) {
            linkUserName.append(hotelOrderAddVo.getLinkUser().get(i).getLinkUserName());
            if (i!=hotelOrderAddVo.getLinkUser().size()-1){
                linkUserName.append(",");
            }
        }
        hotelOrder.setLinkUserName(linkUserName.toString());
        Integer id;
        if (hotelOrderAddVo.getId()!=null){
            OrderLinkUser orderLinkUser = new OrderLinkUser();
            orderLinkUser.setOrderId(hotelOrderAddVo.getId());
            orderLinkUserMapper.delete(orderLinkUser);
            hotelOrder.setModifiedBy(jsonObject.getLong("id"));
            hotelOrder.setModifyDate(new Date());
            id = hotelOrderMapper.updateByPrimaryKeySelective(hotelOrder);
        }else {
            id = hotelOrderMapper.insertOrder(hotelOrder);
        }
        if (id>0){
            for (OrderLinkUser olu:hotelOrderAddVo.getLinkUser()) {
                olu.setOrderId(Long.valueOf(id.toString()));
                olu.setLinkUserId(olu.getId());
                olu.setId(null);
                orderLinkUserMapper.insert(olu);
            }
            return DtoUtils.getSuccesWithData(hotelOrder,"生成订单成功");
        }
        return DtoUtils.getFalseDto("生成订单失败","30004");
    }

    @Override
    public Dto queryOrderById(Long orderId) {
        HotelOrder hotelOrder = hotelOrderMapper.selectByPrimaryKey(orderId);
        if (hotelOrder!=null){
            return DtoUtils.getSuccesWithData(hotelOrder,"获取订单成功");
        }
        return DtoUtils.getFalseDto("获取订单失败","30005");
    }

}
